package ms.pms.service;

import com.github.pagehelper.PageHelper;
import ms.common.exception.BizException;
import ms.common.page.Page;
import ms.common.util.bean.BeanUtil;
import ms.common.util.string.StringUtil;
import ms.pms.bean.BindPermissionParamBean;
import ms.pms.bean.CommonQueryParamBean;
import ms.pms.bean.RoleParamBean;
import ms.pms.config.ResponseCode;
import ms.pms.dao.PermissionDAO;
import ms.pms.dao.RoleDAO;
import ms.pms.dao.RolePermissionDAO;
import ms.pms.dao.UserRoleDAO;
import ms.pms.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Project Name: ms
 * File Name: RoleService
 * Package Name: ms.pms.service
 * Date: 2018/6/21  16:37
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Service
public class RoleService {

    @Autowired
    private RoleDAO roleDAO;

    @Autowired
    private PermissionDAO permissionDAO;

    @Autowired
    private RolePermissionDAO rolePermissionDAO;

    @Autowired
    private UserRoleDAO userRoleDAO;
    /**
     * 查询角色信息
     * @param commonQueryParamBean
     * @return
     */
    public Page<Role> query(CommonQueryParamBean commonQueryParamBean) {
        com.github.pagehelper.Page page = PageHelper.startPage(commonQueryParamBean.getPageNo(), commonQueryParamBean.getPageSize());
        List<Role> roles = roleDAO.query(commonQueryParamBean.getStatus(), commonQueryParamBean.getName());
        return new Page(page.getPageNum(), page.getPageSize(), (int)page.getTotal(), roles);
    }

    /**
     * 角色列表
     * @param commonQueryParamBean
     * @return
     */
    public List<Role> list(CommonQueryParamBean commonQueryParamBean) {
        List<Role> roles = roleDAO.query(commonQueryParamBean.getStatus(), "");

        if(0L == commonQueryParamBean.getOptId()) {
            return roles;
        }
        UserRole param = new UserRole();
        param.setUserId(commonQueryParamBean.getOptId());
        UserRole userRole = userRoleDAO.selectOne(param);
        if(null == userRole) {
            return roles;
        }

        Long roleId = userRole.getRoleId();
        for (Role role: roles) {
            if(roleId == role.getId()) {
                role.setStatus(10);
                break;
            }
        }
        return roles;
    }

    /**
     * 保存角色信息
     * @param roleParamBean
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void save(RoleParamBean roleParamBean) {
        Long id = roleParamBean.getId();
        //查询角色是否存在
        Role role = roleDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(role)) {//新增
            Role param = BeanUtil.copy(roleParamBean, Role.class);
            param.setCreateTime(System.currentTimeMillis());

            roleDAO.insert(param);
            return;
        }
        //修改
        role.setName(roleParamBean.getName());

        roleDAO.updateByPrimaryKey(role);
    }

    /**
     * 启用
     * @param id
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void use(Long id) {
        //查询角色是否存在
        Role role = roleDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(role)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色不存在");
        }
        if(1 == role.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色状态错误");
        }
        role.setStatus(1);
        roleDAO.updateByPrimaryKey(role);
    }

    /**
     * 停用
     * @param id
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void cancel(Long id) {
        //查询角色是否存在
        Role role = roleDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(role)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色不存在");
        }
        if(2 == role.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色状态错误");
        }
        role.setStatus(2);
        roleDAO.updateByPrimaryKey(role);
    }

    /**
     * 删除
     * @param id
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void delete(Long id) {
        //查询角色是否存在
        Role role = roleDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(role)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色不存在");
        }
        if(1 == role.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色状态错误");
        }
//        role.setStatus(3);
//        roleDAO.updateByPrimaryKey(role);
        roleDAO.deleteByPrimaryKey(role.getId());
    }

    /**
     * 分配权限
     * @param bindPermissionParamBean
     */
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
    public void bind(BindPermissionParamBean bindPermissionParamBean) {
        Role role = roleDAO.selectByPrimaryKey(bindPermissionParamBean.getRoleId());
        if(StringUtil.isEmpty(role)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色不存在");
        }
        if(1 == role.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "请先停用该角色");
        }
        //获取权限集合
        List<Long> permissionIds = bindPermissionParamBean.getPermissionIds();
        //校验是否有非法权限
        List<Permission> permissions = permissionDAO.selectPermissionsByIds(permissionIds);
        if(permissionIds.size() != permissions.size()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "权限有误！");
        }

        List<RolePermission> rolePermissions = new ArrayList<>();
        Long roleId = bindPermissionParamBean.getRoleId();

        //删除原来的关联
        RolePermission rolePermissionParam = new RolePermission();
        rolePermissionParam.setRoleId(roleId);
        rolePermissionDAO.delete(rolePermissionParam);

        permissionIds.forEach(permissionId -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(permissionId);
            rolePermission.setRoleId(roleId);

            rolePermissions.add(rolePermission);
            rolePermissionDAO.insert(rolePermission);
        });

//        rolePermissionDAO.insertList(rolePermissions);
    }

    /**
     * 查询角色详情
     * @param id
     * @return
     */
    public Role detail(Long id) {
        //查询角色是否存在
        Role role = roleDAO.selectByPrimaryKey(id);
        if(StringUtil.isEmpty(role)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "角色不存在");
        }
        return role;
    }

}
